package grdnlog.controller;

import grdnlog.bean.GardenLogConfig;
import grdnlog.service.GardenLogService;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@RequestMapping("/log-config")
@Controller
public class GardenLogConfigController {

	@Autowired
	private GardenLogService gardenLogService;
	
	@ModelAttribute("config")
	public GardenLogConfig setupForm() {
		return new GardenLogConfig();
	}

	@ModelAttribute("configs")
	public List<GardenLogConfig> populateConfigs() {
		final UserService userService = UserServiceFactory.getUserService();
		
		if (userService.isUserLoggedIn()) {
			User user = userService.getCurrentUser();
			List<GardenLogConfig> results = gardenLogService.getGardenLogConfigs(user.getEmail());
			return new ArrayList<GardenLogConfig>(results);
		} else {
			return new ArrayList<GardenLogConfig>();
		}
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public String home() {
		return "log-config";
	}
	
	@RequestMapping(params = "delete-config", method = RequestMethod.POST)
	public String deleteConfig(@RequestParam("id") String configId, GardenLogConfig config, BindingResult result, SessionStatus status) {
		//TODO prevent deleting other user's configs
		final String userId = "does nothing";
		try {
			gardenLogService.deleteGardenLogConfig(configId, userId);
			status.setComplete();
		} catch (Exception e) {
			result.reject("error.config.delete", e.getLocalizedMessage());
		}
		
		return "redirect:log-config";
	}
	
	@RequestMapping(params = "save", method = RequestMethod.POST)
	public String save(@Valid GardenLogConfig config, BindingResult result, SessionStatus status) {
				
		if (result.hasErrors()) {
			return "log-config";
		} else {
			final UserService userService = UserServiceFactory.getUserService();
			
			if (userService.isUserLoggedIn()) {
				User user = userService.getCurrentUser();
				config.setUserId(user.getEmail());
				gardenLogService.saveGardenLogConfig(config);
			} else {
				result.reject("You must be logged in!");
				return "log-config";
			}	
			
			return "redirect:log-config";
		}
	}
	
}
